package cn.bugio.note.controller.user;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.bugio.note.auth.CheckLogin;
import cn.bugio.note.common.domain.dto.UserDTO;
import cn.bugio.note.common.vo.ServerResponse;
import cn.bugio.note.domain.data.TokenInfo;
import cn.bugio.note.domain.dto.user.JwtTokenRespDTO;
import cn.bugio.note.domain.dto.user.LoginRespDTO;
import cn.bugio.note.domain.dto.user.UserLoginReqDTO;
import cn.bugio.note.domain.dto.user.UserRespDTO;
import cn.bugio.note.domain.entity.user.User;
import cn.bugio.note.service.user.UserService;
import cn.bugio.note.util.JwtOperator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Vincent Vic
 * @version 1.0
 * @Description
 * @since 2021/2/16
 */

@RestController
@RequestMapping("/users/")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private JwtOperator jwtOperator;

    @GetMapping("{id}")
    @ResponseBody
    @CheckLogin
    public ServerResponse<UserDTO> findById(@PathVariable Integer id){

        log.info("id : {}" ,id);
        if (id == null){
            return ServerResponse.error("参数不能为空");
        }
        ServerResponse<UserDTO> userDTOServerResponse = userService.findById(id);
        log.info("user dto -> {} ",userDTOServerResponse);
        return userDTOServerResponse;
    }

    @GetMapping("t-token")
    @ResponseBody
    @CheckLogin
    public ServerResponse<UserDTO> testToken( Integer id,String wxNickname, String roles) {
        return ServerResponse.success(
                UserDTO.builder()
                        .id(id)
                        .wxNickname(wxNickname)
                        .roles(roles)
                        .build()
        );

    }

    @GetMapping("t-token2")
    @ResponseBody
    @CheckLogin
    public ServerResponse<UserDTO> testToken2(HttpServletRequest request) {
        return ServerResponse.success(
                UserDTO.builder()
                        .id((Integer) request.getAttribute("id"))
                        .wxNickname((String) request.getAttribute("wxNickname"))
                        .roles((String) request.getAttribute("roles"))
                        .build()
        );

    }


    @GetMapping("token")
    @ResponseBody
    public ServerResponse<LoginRespDTO> genToken() {
        ServerResponse<UserDTO> response = userService.findById(1);

        if (!response.isSuccess()) {
            return ServerResponse.error("用户不存在");
        }
        UserDTO user = response.getData();

        TokenInfo tokenInfo = TokenInfo.builder()
                .id(user.getId())
                .wxNickname(user.getWxNickname())
                .roles(user.getRoles())
                .build();
        String json = JSONObject.toJSONString(tokenInfo);

        Map<String, Object> userInfo = JSON.parseObject(json,Map.class);
        String token = jwtOperator.generateToken(userInfo);

        log.info("用户 【{}】 登入成功，生成token ==> {},有效期到:{}",user.getWxNickname(),token,jwtOperator.getExpirationTime());

        return ServerResponse.success(LoginRespDTO.builder()
                .token(
                        JwtTokenRespDTO.builder()
                                .token(token)
                                .expirationTime(jwtOperator.getExpirationTime().getTime())
                                .build()
                )
                .user(
                        UserRespDTO.builder()
                                .id(user.getId())
                                .avatarUrl(user.getAvatarUrl())
                                .wxNickname(user.getWxNickname())
                                .bonus(user.getBonus())
                                .build()
                )
                .build());
    }

    @PostMapping("login")
    @ResponseBody
    public ServerResponse<LoginRespDTO> login(UserLoginReqDTO userLoginReqDTO) throws WxErrorException {

//        //请求api
//        //微信小程序服务端校验是否已经登录的结果
//        WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(userLoginReqDTO.getCode());
//        //微信的openId，用户在微信这边的唯一 标示
//        String openid = result.getOpenid() ;
//
//        ServerResponse<User> login = userService.login(userLoginReqDTO, openid);
//
//        if (!login.isSuccess()){
//
//
//        }
//
//        User user = login.getData();

        ServerResponse<UserDTO> response = userService.findById(Integer.valueOf(userLoginReqDTO.getCode()));

        if (!response.isSuccess()) {
            return ServerResponse.error("用户不存在");
        }
        UserDTO user = response.getData();

        TokenInfo tokenInfo = TokenInfo.builder()
                .id(user.getId())
                .wxNickname(user.getWxNickname())
                .roles(user.getRoles())
                .build();
        String json = JSONObject.toJSONString(tokenInfo);

        Map<String, Object> userInfo = JSON.parseObject(json,Map.class);
        String token = jwtOperator.generateToken(userInfo);

        log.info("用户 【{}】 登入成功，生成token ==> {},有效期到:{}",user.getWxNickname(),token,jwtOperator.getExpirationTime());

        return ServerResponse.success(LoginRespDTO.builder()
                .token(
                        JwtTokenRespDTO.builder()
                                .token(token)
                                .expirationTime(jwtOperator.getExpirationTime().getTime())
                                .build()
                )
                .user(
                        UserRespDTO.builder()
                                .id(user.getId())
                                .avatarUrl(user.getAvatarUrl())
                                .wxNickname(user.getWxNickname())
                                .bonus(user.getBonus())
                                .build()
                )
                .build());
    }
}
